package com.wendyxie.sproutup.db

import android.content.Context
import android.database.sqlite.SQLiteDatabase
import com.wendyxie.sproutup.entity.TreeEntity
import com.wendyxie.sproutup.entity.UserEntity
import com.wendyxie.sproutup.entity.UserScoreRecordEntity
import com.wendyxie.sproutup.entity.UserTreeEntity
import com.wendyxie.sproutup.enum.ScoreStatusEnum
import com.wendyxie.sproutup.utils.SPUtil

class SQLUserDomainHelper {

    companion object {
        /**
         * 添加用户得分记录
         */
        fun addUserScoreRecord(userScoreRecordEntity: UserScoreRecordEntity, babyId: String, db: SQLiteDatabase) {
            val userEntity = SQLUserHelper.queryBabyById(babyId, db) ?: return
            // 1. 新增记录
            userScoreRecordEntity.babyId = babyId
            userScoreRecordEntity.userId = userEntity.userId
            userScoreRecordEntity.totalScoreStart = userEntity.currentTotalScore
            userScoreRecordEntity.totalScoreEnd = userEntity.currentTotalScore + userScoreRecordEntity.score
            SQLUserScoreRecordHelper.addUserScoreRecord(userScoreRecordEntity, db)
            // 2. 在用户信息中追加
            userEntity.currentTotalScore += userScoreRecordEntity.score
            userEntity.currentReceivedScore += userScoreRecordEntity.score
            SQLUserHelper.updateUserById(userEntity, db)
        }

        /**
         * 收集用户得分记录
         */
        fun collectUserScoreRecord(userScoreRecordEntity: UserScoreRecordEntity, db: SQLiteDatabase) {

        }

        fun exchangeTree(tree: TreeEntity, userId: String, babyId: String, db: SQLiteDatabase) {
            val userEntity = SQLUserHelper.queryBabyById(babyId, db) ?: return
            // 1. 添加减分记录
            val userScoreRecordEntity = UserScoreRecordEntity(
                userId = userEntity.userId,
                babyId = babyId,
                score = -tree.treePrice,
                scoreTitle = "兑换${tree.treeName}",
                scoreTmplId = tree.treeId
            )
            userScoreRecordEntity.scoreStatus = ScoreStatusEnum.COLLECT
            addUserScoreRecord(userScoreRecordEntity, babyId, db)
            // 2. 添加兑换记录
            SQLUserTreeHelper.addUserTree(UserTreeEntity(userId, babyId, tree.treeId, tree.treePrice, tree.treeName, tree.treeImageUrl), db)
            // 3. 减少用户积分
            userEntity.currentTotalScore -= tree.treePrice
            userEntity.currentReceivedScore -= tree.treePrice
            SQLUserHelper.updateUserById(userEntity, db)
        }
    }


}
